let app = getApp();
let API_URL = app.globalData.API_URL;
import { getRepairShop, getRepairShopDetail } from "../../../request/api.js";
import dayjs from "../../../common/js/dayjs.js";

let iconUrl = 'https://atush.vip/static/icons/';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        lang: null,
        isAuthenticate: true,
        topTapCurrentIndex: 0,
        currentIndex: 0,
        showAuthDialog: false,
        showUnfilledDialog: false,
        showSuccessPromptDialog: false,
        showFailPromptDialog: false,
        maintenance: [],
        review: [],
        iconUrl: iconUrl,
        tips: {
            title_ug: 'سەمىمىي ئەسكەرتىش',
            title_zh: '温馨提示',
            content_ug: 'ئاتۇش ئۇچۇر سۇپىمىز شەخسىي ئۇچۇرىڭىزنى قوغدايدۇ .سىز ئۈچۈن تېخىمۇ ئىشەنچىلىك ، بىخەتەر بولغان ئۇچۇر تەمىنلەش ئۈچۈن ئۇچۇر يوللاشتىن بۇرۇن سالاھىتىڭىزنى دەلىللەڭ. سالاھىيەت دەلىللەنگەندىن كىيىن ئۇچۇر سۇپىمىزغا ئۇچۇر يوللىيالايسىز .',
            content_zh: '阿图什信息平台保护您的隐私。为了更提供高质量，可靠的信息发布信息前需要实名认证。'
        },
        review1: [],
        filterMaintenance: [
            {id: 1, name: 'all', icon: iconUrl + 'quanbu.svg'},
            {id: 2, name: 'furnish', icon: iconUrl +'zhuangxiu.svg'},
            {id: 3, name: 'repair', icon: iconUrl +'weixiu.svg'},
            {id: 4, name: 'design', icon: iconUrl +'sheji.svg'}
        ],
        filterActive: 0,
        filterType: -1,
        currentItemIndex: null,
        editId: null,
        destroyId: null,
        userId: 0,
        showUp_loading: false,
        showDeletePhoto: false,
        photoId: 0,
        delIndexPhoto: 0,
        iSallow_dialog: false,
        code: null,
        phoneNum: null,
        isShowAuthrity: false, // 用光发布信息提醒

        // 分页
        pageNo: 1,
        totalPage: 0,

        uploadImages: [],
        files: [],
        // 填空
        infoObj :{}
    },

    /**
     * My Function
     */

    // 筛选
    onCilckMaintenanceFilter(item) {
        this.setData({ filterActive: item.currentTarget.dataset.index, maintenance: [] })
        switch (this.data.filterActive) {
            case 0:
                this.setData({ filterType: -1 })
                this.homePage()
                break;
            case 1:
                this.setData({ filterType: 21 })
                this.homePage()
                break;
            case 2:
                this.setData({ filterType: 22 })
                this.homePage()
                break;
            case 3:
                this.setData({ filterType: 23 })
                this.homePage()
                break;
            default:
                break;
        }
    },

    // 获取手机号并且保存
    getTel(e) {
        if (e == undefined) return;
        let that = this;
        
        if (e.detail.errMsg == "getPhoneNumber:ok") {
            wx.request({
                url: `${API_URL}/v1/getPhoneNumber`,
                data: { encryptedData: e.detail.encryptedData, iv: e.detail.iv, code: that.data.code },
                method: 'post',
                success: function (res) {
                    let userId = wx.getStorageSync('userInfo').user.id;
                    let phoneNum = res.data.phoneNumber
                    let data = { userId, phoneNum }
                    wx.request({
                        url: `${API_URL}/userUpdate`,
                        data: data,
                        method: 'POST',
                        success: function (res) {
                            that.sendBTN()
                        }
                    })
                },
                fail: res => {
                    console.log("fail:");
                }
            })
        } else {
            this.setData({ iSallow_dialog: true })
        }
    },

    // 关闭获取手机号提示
    allowDialog_finish() {
        this.setData({ iSallow_dialog: false })
    },

    // 快速登陆获取 code
    sudoLogin() {
        wx.login({
            success: (res) => {
                this.setData({ code: res.code })
            }
        })
    },

    // 定时登录获取 code、并且从数据库获取手机号
    timingLogin() {
        let that = this;
        that.sudoLogin();

        wx.request({
            url: `${API_URL}/getUserCon`,
            data: { userId: wx.getStorageSync('userInfo').user.id },
            method: 'POST',
            success: function (res) {
                that.setData({ phoneNum: res.data.phoneNum });
            }
        })

        setInterval(function() {
            that.sudoLogin();
        }, 200000)
    },

    // 获取手机号后发送
    sendCon() {
        this.getTel();
    },

     // 等待上传
    waitForUpload() {
        let that = this
        setTimeout(function () {
            that.setData({ showUp_loading: false })
        }, 5000);
    },

    // 发送
    sendBTN() {
        let id = this.data.infoObj.id
        let userId = this.data.userId
        let name_ug = this.data.infoObj.name_ug
        let contactPerson_ug = this.data.infoObj.contactPerson_ug
        let lectureRange_ug = this.data.infoObj.lectureRange_ug
        let weChat = this.data.infoObj.weChat
        let phoneNum = this.data.infoObj.phoneNum
        let detailed_ug = this.data.infoObj.detailed_ug
        let image_id = this.data.infoObj.image_id
        let data = {
            id: id,
            user_id: userId,
            name_ug,
            lectureRange_ug,
            detailed_ug,
            contactPerson_ug,
            weChat,
            phoneNum,
            image_id:image_id
        }
        if (
            name_ug == undefined ||
            name_ug == '' ||
            lectureRange_ug == undefined ||
            lectureRange_ug == '' ||
            contactPerson_ug == undefined ||
            contactPerson_ug == '' ||
            weChat == undefined ||
            weChat == '' ||
            phoneNum == undefined ||
            phoneNum == '' ||
            detailed_ug == undefined ||
            detailed_ug == ''
        ) {
            return this.setData({ showUnfilledDialog: true })
        }
        this.setData({ showUp_loading: true })
        this.waitForUpload()
        let that = this
        wx.request({
            url: `${API_URL}/repairShop`,
            data: data,
            header: app.header(),
            method: 'post',
            success: function (res) {
                if(res.data.status == 411) {
                    that.setData({ isShowAuthrity: true, showUp_loading: false })
                    return;
                }
                if (res.statusCode == 200) {
                    let insertId = res.data.insertId
                    if (insertId == 0) {
                        that.uploadTempImages(that.data.editId, 10);
                    } else {
                        that.uploadTempImages(res.data.insertId, 10);
                    }
                    setTimeout(function () {
                        that.setData({ showSuccessPromptDialog: true, infoObj: {}, uploadImages: [] });
                    }, 5000)
                }
            },
            fail: function() {
                setTimeout(function() {
                    that.setData({ showFailPromptDialog: true })
                }, 3000)
            }
        })
    },

    // 上传照片
    uploadTempImages(targetId, targetType) {
        for (const item of this.data.uploadImages) {
            wx.uploadFile({
                url: `${API_URL}/repairShopFiles`,
                filePath: item.fullUrl,
                header: app.header(),
                name: 'file',
                formData: {
                    'target_id': targetId,
                    'target_type': targetType
                },
                success(res) {
                    const data = res.data
                }
            })
        }
    },

    // 添加照片
    uploadImage() {
        let that = this;
        let imgArr = this.data.uploadImages;
        wx.chooseImage({
            count: 5,
            success(res) {
                const tempFilePaths = res.tempFilePaths
                for (const item of tempFilePaths) {
                    if ( imgArr.length == 5 ) {
                        console.log('已经 5 个照片了');
                        break
                    }
                    let data = {}
                    data.fullUrl = item
                    imgArr.push(data)
                }
                that.setData({
                    uploadImages: imgArr
                })
            }
        })
    },

    name_ug(e){
        this.data.infoObj.name_ug = e.detail.value
        this.setData({infoObj : this.data.infoObj})
    },

    lectureRange_ug(e){
        this.data.infoObj.lectureRange_ug = e.detail.value
        this.setData({infoObj : this.data.infoObj})
    },

    contactPerson_ug(e){
        this.data.infoObj.contactPerson_ug = e.detail.value
        this.setData({infoObj : this.data.infoObj})
    },

    weChat(e){
        this.data.infoObj.weChat = e.detail.value
        this.setData({infoObj : this.data.infoObj})
    },

    phoneNum(e){
        this.data.infoObj.phoneNum = e.detail.value
        this.setData({infoObj : this.data.infoObj})
    },

    detailed_ug(e){
        this.data.infoObj.detailed_ug = e.detail.value
        this.setData({infoObj : this.data.infoObj})
    },

    /**
     * 删除发布内容
     */
    // 获取 Id
    getIndexById(id, arr) {
        this.setData({ destroyId: id })
        for( let i in arr ) {
            if( id == arr[i].id ) {
                return i;
            }
        }
        return -1;
    },

    // 确定删除对
    dialogOnConfirm() {
        let token = null;
        let destroyId = this.data.destroyId;
        wx.getStorage({
            key: 'userInfo',
            success(res) {
                token = res.data.token
                wx.request({
                    url: `${API_URL}/repairShopDestroy`,
                    header: app.header(),
                    data: { postId: destroyId },
                    method: 'post',
                    success: function (res) {}
                })
            }
        })

        if (this.data.currentItemIndex) {
            let index = this.data.currentItemIndex
            let arr = this.data.review
            arr.splice(index, 1)
            this.setData({ review: arr })
        }
        this.setData({ showAuthDialog: false })
    },

    // 取消删除
    dialogOnCancel() {
        this.setData({ showAuthDialog: false })
    },

    // 弹出删除对话框
    showDialogtTap(e) {
        let item = e.currentTarget.dataset.item
        this.setData({
            showAuthDialog: true,
            currentItemIndex: this.getIndexById(item.id, this.data.review)
        })
    },

    // 完毕对话框
    dialogOnComplete() {
        this.setData({ showUnfilledDialog: false })
    },

    // 成功提示框完毕
    completeDialog() {
        this.setData({ showSuccessPromptDialog: false })
    },

    // 失败提示框完毕
    failCompleteDialog() {
        this.setData({ showFailPromptDialog: false })
    },
    
    // 编辑内容 
    onEdit(item) {
        let postId = item.currentTarget.dataset.item.id
        let data = { postId }
        getRepairShopDetail(res => {
            let editId = res.data.id
            let imgArr = res.data.images
            this.setData({ currentIndex: 1, infoObj: res.data, uploadImages: imgArr, editId: editId, userId: wx.getStorageSync('uid') })
        }, data);
    },

    // 首页
    homePage() {
        let status = 1
        let type = this.data.filterType
        let data = { status, type, pageNo : this.data.pageNo }
        getRepairShop(res => {
            let request = res.data.data
            if (res.statusCode == 200) {
                this.setData({ maintenance: this.data.maintenance.concat(request), totalPage : res.data.totalPage })
            }
        }, data);
    },

    // 全部发送
    allPush() {
        let data = { currentUser:true }
        getRepairShop(res => {
            let request = res.data.data
            if (res.statusCode == 200) {
                for (let item of res.data.data) {
                    item.releaseTime = dayjs(item.releaseTime).format("YYYY-MM-DD")
                }
                this.setData({ review: request })
            }
        }, data);
    },

    // 待审核
    pendingReview() {
        let data = { status: 0, currentUser:true }
        getRepairShop(res => {
            let request = res.data.data
            if (res.statusCode == 200) {
                this.setData({ review1: request })
            }
        }, data);
    },

    //用户点击bottomTab时调用
    titleClick: function (e) {
        let index = e.currentTarget.dataset.idx
        
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 0
        })
        let checkAuth = false;
        switch (index) {
            case '0':
                this.homePage()
                break;
            case '1':
                app.login()
                this.timingLogin()
                checkAuth = true
                break;
            case '2':
                let promise = new Promise(function(resolve, rej) {
                    app.login(res => {
                        resolve(res)
                    })
                })
                
                checkAuth = true
                promise.then(
                    resolve => {
                        this.allPush()
                    }
                )
                break;
            default:
                break;
        }
        let info = wx.getStorageSync('userInfo')
        if (info) {
            this.setData({ userId: wx.getStorageSync('userInfo').user.id })
        }
        if (checkAuth && this.data.userId == 0) return
        this.setData({ currentIndex: e.currentTarget.dataset.idx, pageNo: 1, maintenance: [] });
    },

    //用户点击topTab时调用
    topTapClick(e) {
        this.setData({ topTapCurrentIndex: e.currentTarget.dataset.index })
        let index = e.currentTarget.dataset.index
        switch (index) {
            case '0':
                this.allPush()
                break;
            case '1':
                this.pendingReview()
                break;
            default:
                break;
        }
    },

    // 跳页到详细页面
    goDetailed(event) {
        let itemId = event.currentTarget.dataset.item.id
        wx.navigateTo({
            url: '/pages/home/maintenance/maintenanceDetailed/maintenanceDetailed?itemId=' + itemId
        });
    },
    
    // 认证
    toAuthenticate() {
        wx.navigateTo({
            url: '/pages/detail/authenticate/authenticate'
          });
    },

    // 移除图片
    destroyPhoto(e) {
        let photoId = e.currentTarget.dataset.item.id
        let delIndexPhoto = e.currentTarget.dataset.index
        this.setData({ photoId: photoId, delIndexPhoto: delIndexPhoto, showDeletePhoto: true })
    },

    // 确定删除编辑照片
    editPhotoOnConfirm() {
        if (this.data.editId !== null) {
            let data = { fileId: this.data.photoId }
            wx.request({
                url:`${API_URL}/getRepairShopFilesFilesId`,
                header: app.header(),
                data: data,
                method: 'post',
                success: function (res) {}
            })

            let arr = this.data.uploadImages
            arr.splice(this.data.delIndexPhoto, 1)
            this.sendBTN()
            this.setData({ uploadImages: arr, showDeletePhoto: false })
        } else {
            let arr = this.data.uploadImages
            arr.splice(this.data.delIndexPhoto, 1)
            this.setData({ uploadImages: arr, showDeletePhoto: false })
        }
    },

    // 取消删除编辑照片
    editPhotoOnCancel() {
        this.setData({ showDeletePhoto: false })
    },

    // 打电话
    telephone(e) {
      let tel = e.currentTarget.dataset.item;
      wx.makePhoneCall({
        phoneNumber: tel,
        fail: cancel => {
            console.log("cancel: ", cancel);
        }
      })
    },

    // App 默认方法


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let currentIndex = 0
        if (options.currentIndex > 0) {
            currentIndex = options.currentIndex;
        }
        this.setData({ lang: app.globalData.lang, navTitle: "maintenanceInfo", navigation: true, currentIndex: currentIndex })
        this.homePage()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.setData({ isShowAuthrity: false })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        if(this.data.currentIndex == 0){
            if(this.data.pageNo == this.data.totalPage) return
            let pageNo = this.data.pageNo += 1
            this.setData({pageNo : pageNo})
            this.homePage();
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})